import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:meco/common/models/user_model.dart';
import 'package:meco/common/utils/storage_utils.dart';
import 'package:meco/common/utils/colors.dart';
import 'package:meco/common/routes/app_pages.dart';
import 'package:meco/views/system/main/controller.dart';
import '../repositories/user_repository.dart';

class UserService extends GetxService {
  final UserRepository _userRepository = UserRepository();

  // 是否已登录
  final RxBool isLoggedIn = false.obs;

  // 当前用户信息
  final Rx<User?> currentUser = Rx<User?>(null);

  // 初始化服务
  Future<UserService> init() async {
    // 确保存储工具已初始化
    await StorageUtils.init();

    // 检查登录状态
    await checkLoginStatus();

    return this;
  }

  // 检查登录状态
  Future<bool> checkLoginStatus() async {
    if (StorageUtils.getBool('is_logged_in') == true) {
      final userId = StorageUtils.getInt('user_id');
      if (userId != null) {
        try {
          final user = await _userRepository.getUserById(userId);
          if (user != null) {
            currentUser.value = user;
            isLoggedIn.value = true;
            return true;
          }
        } catch (e) {
          print('获取用户信息失败: $e');
        }
      }
      // 登录状态无效，清除
      await logout();
    }
    return false;
  }

  // 保存用户登录状态
  Future<void> saveLoginState(User user) async {
    // 保存用户ID
    await StorageUtils.setInt('user_id', user.id!);
    // 保存用户名
    await StorageUtils.setString('username', user.username);
    // 保存登录状态
    await StorageUtils.setBool('is_logged_in', true);

    // 更新状态
    currentUser.value = user;
    isLoggedIn.value = true;
  }

  // 退出登录
  Future<void> logout() async {
    // 清除登录状态
    await StorageUtils.remove('user_id');
    await StorageUtils.remove('username');
    await StorageUtils.remove('is_logged_in');

    // 更新状态
    currentUser.value = null;
    isLoggedIn.value = false;
  }

  // 检查登录状态并执行操作
  Future<bool> checkLoginThenExecute({
    required Function() onLoggedIn,
    String? loginRequiredMessage,
  }) async {
    if (isLoggedIn.value) {
      // 已登录，执行操作
      onLoggedIn();
      return true;
    } else {
      // 未登录，记录当前路由并跳转到登录页
      final currentRoute = Get.currentRoute;
      final currentArguments = Get.arguments;

      // 弹出登录提示对话框
      final shouldLogin = await Get.dialog<bool>(
        _buildLoginDialog(loginRequiredMessage ?? 'Login required to continue'),
        barrierDismissible: false,
      );

      if (shouldLogin == true) {
        // 用户选择登录
        Get.toNamed(
          Routes.login,
          arguments: {
            'returnRoute': currentRoute,
            'returnArguments': currentArguments,
          },
        );
      }
      return false;
    }
  }

  // 构建登录提示对话框
  Widget _buildLoginDialog(String message) {
    return Dialog(
      backgroundColor: AppColors.primary,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
        side: BorderSide(color: AppColors.secondary, width: 2),
      ),
      child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              'Login Required',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18,
                fontWeight: FontWeight.w500,
              ),
            ),
            SizedBox(height: 16),
            Text(message, style: TextStyle(color: Colors.white, fontSize: 16)),
            SizedBox(height: 24),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                TextButton(
                  onPressed: () => Get.back(result: false),
                  style: TextButton.styleFrom(foregroundColor: Colors.white70),
                  child: Text('Cancel', style: TextStyle(fontSize: 16)),
                ),
                SizedBox(width: 16),
                Container(
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [AppColors.secondary, AppColors.accent],
                    ),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: TextButton(
                    onPressed: () => Get.back(result: true),
                    style: TextButton.styleFrom(
                      foregroundColor: Colors.white,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20),
                      ),
                      padding: EdgeInsets.symmetric(horizontal: 16),
                    ),
                    child: Text('Login Now', style: TextStyle(fontSize: 16)),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 登录后导航回上一页
  void navigateBackAfterLogin() {
    final arguments = Get.arguments;
    if (arguments != null && arguments is Map) {
      final returnRoute = arguments['returnRoute'];
      final returnArguments = arguments['returnArguments'];

      if (returnRoute != null) {
        // 如果是主页中的标签页，需要特殊处理
        if (returnRoute.startsWith('/main')) {
          Get.offAllNamed(Routes.main);

          // 根据路由设置底部导航选中项
          Future.delayed(Duration(milliseconds: 100), () {
            final mainController = Get.find<MainController>();
            switch (returnRoute) {
              case Routes.home:
                mainController.changePage(0);
                break;
              case Routes.time:
                mainController.changePage(1);
                break;
              case Routes.share:
                mainController.changePage(2);
                break;
              case Routes.me:
                mainController.changePage(3);
                break;
            }
          });
        } else {
          // 其他页面直接返回
          Get.offAndToNamed(returnRoute, arguments: returnArguments);
        }
        return;
      }
    }

    // 默认情况，返回主页
    Get.offAllNamed(Routes.main);
  }
}
